<?php
class WeChat{
    protected $appid;
    protected $appsecret;
    public function __construct($appid,$appsecret) {
        //给appid和appsecret赋值
        $this->appid = $appid;
        $this->appsecret = $appsecret;

        //自动调用消息处理函数
        // $this->responseMsg();
    }
    //token验证
    public function valid() {
        $echostr = $_GET['echostr'];
        if($this->checkSignature()) {
            echo $echostr;
        }else {
            echo "error";
            exit;
        }
    }
    //token验证规则
    public function checkSignature() {
        $signature = $_GET['signature'];
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        //字典序排序
        $tmpArr = array(TOKEN,$timestamp,$nonce);
        sort($tmpArr,SORT_STRING);
        //拼接字符串sha1加密
        $tmpStr = join($tmpArr);
        $tmpStr = sha1($tmpStr);
        //加密签名的比较
        if ($tmpStr == $signature) {
            return true;
        }else {
            return false;
        }
    }
    // 获取access_token
	public function get_access_token(){
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
		$request=$this->https_request($url);
        // var_dump($request);
        // exit;
		return $request['access_token'];
	}

	// 模拟gei请求·和post请求
	public function https_request($url,$data=""){
		 // 开启curl
		 $ch=curl_init();
		 // 设置传输选项
		 // 设置传输地址
		 curl_setopt($ch, CURLOPT_URL, $url);
		 // 以文件流的形式返回
		 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		 if ($data) {
		 	// 以post方式
 			 curl_setopt($ch, CURLOPT_POST, 1);
 			 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		 }
		 
		 // 发送curl
		 $request=curl_exec($ch);

		 $tmpArr=json_decode($request,TRUE);
		
		if (is_array($tmpArr)) {
			return $tmpArr;
		}else{
			return $request;
		}
		 // 关闭资源
		 curl_close($ch);
	}
    // 创建菜单
	public function menu_create($data){
		$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$this->get_access_token()}";
		return $request=$this->https_request($url,$data);

	}  
}